<template>
  <div class="competitions-container">
    <!-- 添加比赛按钮 -->
    <div class="add-button">
      <el-button type="primary" icon="el-icon-plus" @click="showAddDialog" round
        >添加比赛</el-button
      >
    </div>

    <!-- 比赛表格 -->
    <el-table
      :data="competitionsData"
      border
      stripe
      style="width: 100%"
      :cell-style="{ padding: '8px' }"
    >
      <el-table-column fixed prop="id" label="ID" width="100">
      </el-table-column>
      <el-table-column prop="name" label="比赛名称" min-width="180">
        <template slot-scope="scope">
          <span class="competition-name">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="category" label="类型" width="120">
        <template slot-scope="scope">
          <el-tag :type="getCategoryTagType(scope.row.category)">
            {{ scope.row.category }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="organizerName" label="主办方" min-width="150">
        <template slot-scope="scope">
          <i class="el-icon-office-building"></i>
          <span>{{ scope.row.organizerName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="startTime" label="开始时间" width="170">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span>{{ formatDate(scope.row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="结束时间" width="170">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span>{{ formatDate(scope.row.endTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button
            @click="handleEdit(scope.row)"
            type="primary"
            size="mini"
            icon="el-icon-edit"
            plain
            >编辑</el-button
          >
          <el-button
            @click="handleDeletecompetition(scope.row)"
            type="danger"
            size="mini"
            icon="el-icon-delete"
            plain
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        @current-change="handlePageChange"
      >
      </el-pagination>
    </div>

    <!-- 添加比赛对话框 -->
    <el-dialog title="添加比赛" :visible.sync="addDialogVisible" width="40%">
      <el-form
        :model="newCompetition"
        label-width="100px"
        ref="competitionForm"
      >
        <el-form-item label="比赛名称">
          <el-input v-model="newCompetition.name"></el-input>
        </el-form-item>
        <el-form-item label="比赛类型">
          <el-select v-model="newCompetition.category" placeholder="请选择">
            <el-option
              v-for="item in categories"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主办方">
          <el-input v-model="newCompetition.organizerName"></el-input>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="newCompetition.startTime"
            type="datetime"
            placeholder="选择日期时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="newCompetition.endTime"
            type="datetime"
            placeholder="选择日期时间"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCompetition()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  reqGetAllCompetition,
  reqAddCompetition,
  reqDeleteCompetition,
  reqUpdateCompetition,
} from "@/api";
export default {
  name: "manageCompetition",
  data() {
    return {
      competitionsData: [],
      total: 0, // 总数据量
      pageSize: 10, // 每页条数
      page: 1, // 当前页码
      addDialogVisible: false, // 添加对话框可见性，
      isEdit: false,
      // 新比赛数据
      newCompetition: {
        id: "",
        name: "",
        category: "",
        organizerName: "",
        startTime: "",
        endTime: "",
      },
      categories: ["理工类", "创新创业类", "人文社科类", "医学类"], // 可选类型
    };
  },
  mounted() { 
      this.handleSearch();
  },
  methods: {
    // 获取比赛类型标签样式
    getCategoryTagType(category) {
      switch (category) {
        case "理工类":
          return "primary";
        case "创新创业类":
          return "success";
        case "人文社科类":
          return "primary";
        case "医学类":
          return "success";
        default:
          return "";
      }
    },
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return "";
      const date = new Date(dateString);
      return `${date.getFullYear()}-${(date.getMonth() + 1)
        .toString()
        .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")} ${date
        .getHours()
        .toString()
        .padStart(2, "0")}:${date.getMinutes().toString().padStart(2, "0")}`;
    },

    async handleSearch() {
      // 统一发送请求并处理响应
      const res = await reqGetAllCompetition({
        page: this.page,
        pageSize: this.pageSize,
      });
      if (res.code === 200) {
        this.competitionsData = res.data.records;
        this.total = res.data.total;
      }
    },
    // 分页处理
    handlePageChange(page) {
      this.page = page;
      this.handleSearch();
    },
    // 编辑比赛
    handleEdit(row) {
      const {compDetailId,organizerId,status,updateTime,...newdata} = {...row}
      this.newCompetition = newdata;
      this.addDialogVisible = true;
      this.isEdit = true;
    },
    async handleDelete(row) {
        console.log(row.id);
      const res = await reqDeleteCompetition(row.id);
    
      if (res.code === 200) {
        this.handleSearch();
      }
    },
    // 删除比赛
    handleDeletecompetition(row) {
      this.$confirm("确定删除该比赛?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.handleDelete(row);
          this.$message.success("删除成功");
        })
        .catch(() => {});
    },
    // 显示添加对话框
    showAddDialog() {
      this.newCompetition = {
        id: "",
        name: "",
        category: "",
        organizerName: "",
        startTime: "",
        endTime: "",
      };
      this.addDialogVisible = true;
    },

    async handleAdd() {
      const { id, ...newData } = { ...this.newCompetition };
      const res = await reqAddCompetition(newData);
      if (res.code === 200) {
        this.handleSearch();
      }
    },
    async handleUpdate() {
      console.log(this.newCompetition);
      const res = await reqUpdateCompetition(this.newCompetition);
      if (res.code === 200) {
        this.handleSearch();
      }
    },
    // 添加比赛或更新比赛
    handleCompetition() {
      if (!this.newCompetition.name || !this.newCompetition.category) {
        this.$message.error("请填写必要信息");
        return;
      }
      if (this.isEdit) {
        this.handleUpdate();
      } else {
        this.handleAdd();
      }
      this.addDialogVisible = false;
      this.isEdit = false;
      this.$message.success("比赛添加成功");
    },
  },
};
</script>

<style scoped lang="scss">
.competitions-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;

  .add-button {
    margin-bottom: 20px;
    text-align: right;
  }

  .competition-name {
    font-weight: 500;
    color: #1a73e8;
  }

  .el-table {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    border-radius: 8px;

    ::v-deep .el-table__header {
      th {
        background-color: #f5f7fa;
        color: #1a1a1a;
        font-weight: 600;
      }
    }
  }

  .pagination {
    margin-top: 20px;
    text-align: center;
  }
}
</style>
